<?php


class RelationHandler {

    private $separador;
    private $separadorIds;
    private $tableName;


    function __construct($nombreTabla,$parametros,$debug=false){
        $this->separadorIds=$parametros['id_char'];
        $this->separador=$parametros['separator'];
        $this->tableName=$nombreTabla;

        if($debug){
            $mensaje="->TableName:$nombreTabla.<> Separator: $this->separador.<>
            IdsSep: $this->separadorIds. <> <-";
            trigger_error($mensaje,E_USER_NOTICE);
        }
    }

    private function validateName($name,$shObject,$ehObject){
    //Nombre debe ser TIPO_ELEMENTO-ID/TIPO_ELEMENTO-ID/...
        $campos=explode($this->separador,$name);
        $nombreNodo="";
        $primeraVuelta=true;
        foreach ($campos as $campo){
            $subCampos=explode($this->separadorIds,$campo);
            if(!$shObject->isElementName($subCampos[0])) return false;
            if(!$ehObject->exists($campo)) return false;
           $nombreNodo=$nombreNodo.$this->separadorIds.$subCampos[0];
        }
        if(!$shObject->isElementName(substr($nombreNodo,1))) return false;
        //if($shObject->isElementName($name)) return $nombreNodo;
        return substr($nombreNodo,1);
    }

    
    public function createRelation($name,$shObject,$ehObject,$debug=false){
        $id1=$this->getId($name);
        if($id1>0){
            if($debug){
                    $mensaje[]="Relation between: $name already exists with id=".$id1;
                }
            $resultado= -1;
        }else{
            if(!$tipo=$this->validateName($name,$shObject,$ehObject)){
                if($debug){
                    $mensaje[]="Relation bettween: $name, can not be created. Function will return -1.";
                }
                $resultado=-1;
            }else{
                //insertar
                $query="INSERT INTO ".$this->tableName." (type,name) VALUES ('".$tipo."','".$name."')";
                $result=DB::query($query);
                if($result) {
                    $query="SELECT id FROM ".$this->tableName." WHERE name='".$name."' AND type='".$tipo."'";
                    $result2=DB::query($query);
                    $row=DB::fetch_assoc($result2);
                    if($debug){
                        $mensaje[]="Relation between: $name, type: $tipo has been created with id:".$row['id'];
                    }
                    $resultado= $row['id'];
                }else {
                    if($debug){
                        $mensaje[]="Relation between: $name, type: $tipo can not be created. Function will return -1.";
                    }
                    $resultado=-1;
                }
            }
        }
        if($debug){
            foreach($mensaje as $mens){
                trigger_error($mens,E_USER_NOTICE);
            }
        }
        return $resultado;

    }


    /**
     *  Check if an element exists on the table or not.
     * @param <type> $name Name of the element to check
     * @return <type> true is exists, false otherwise.
     */
    public function exists($name){
        $nombreTabla=$this->tableName;
        $query="SELECT count(*) FROM ".$nombreTabla." WHERE name='".$name."'";
        $result=DB::query($query);
        if(!$result)return false;
        if(DB::num_rows($result)>0){
            $row=DB::fetch_assoc($result);
            if($row['count(*)']==0) return false; //Elemento no existe
            else return true;
        }else return false;
     }


    /**
     *This function returns the id of an element with a given name
     * @param <type> $name Name of the element to return.
     * @return <type> id of the returned node.
     */
    public function getId($relationName){
        $nombreTabla=$this->tableName;
        $query="SELECT id FROM ".$nombreTabla." WHERE name='".$relationName."'";
        $result=DB::query($query);
        if(DB::num_rows($result)!=0){
            $row=DB::fetch_assoc($result);
            return $row['id'];
        }
        else return -1;
    }


    /**
     * Function that deletes the element named $name and its data.
     * @param string $relationName
     * @return boolean true if any row has been deleted.
     */
    public function delete($relationName,$debug=false){
        $nombreTabla=$this->tableName;
        $id=$this->getId($relationName);
        if($id<0){
            if($debug)$mensaje="Relation $relationName don't exist. Function will return false.";
            $resultado=false;
        }
        else {
            $query="DELETE FROM ".$nombreTabla." WHERE id=".$id;
            $resultado=DB::query($query);
            if($debug){
                if($resultado){
                    $mensaje="Relation: $relationName Has been deleted. Function will return true.";
                }else{
                    $mensaje="Relation: $relationName Has not been deleted. Function will return false.";
                }
            }

        }
         trigger_error($mensaje,E_USER_NOTICE);
         return $resultado;
    }

    public function getRelation($name){
        $campos=explode($this->separador,$name);
        $tipo="";
        $nombre="";
        for ($i=0;$i<count($campos);$i++){
            $params=explode($this->separadorIds,$campos[$i]);
            $tipo=$tipo.$this->separadorIds.$params[0];
            $nombre=$nombre.$this->separador.str_replace('?', '%', $campos[$i]);

        }

       

        $query="SELECT name FROM ".$this->tableName. " WHERE name LIKE '".substr($nombre,1)."' AND type='".substr($tipo,1)."'";
        $result=DB::query($query);
        $salida=array();
        if(DB::num_rows($result)>0){
            while($row=DB::fetch_assoc($result)){
                $salida[]=$row['name'];
            }
        }
        echo "Tipo $tipo NOMBRE $nombre <BR>";
        echo "$query <BR>";
        return $salida;
    }


}
?>
